package com.shchuangzhi.smartguard.fragment;


import android.os.Bundle;
import android.app.Fragment;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.elvishew.xlog.XLog;
import com.shchuangzhi.smartguard.R;
import com.shchuangzhi.smartguard.core.CheckInOutResult;
import com.shchuangzhi.smartguard.core.Consts;
import com.shchuangzhi.smartguard.core.DBHelper;
import com.shchuangzhi.smartguard.core.Job;
import com.shchuangzhi.smartguard.core.JobManager;
import com.shchuangzhi.smartguard.core.Machine;
import com.shchuangzhi.smartguard.core.Mode;
import com.shchuangzhi.smartguard.core.Notify;
import com.shchuangzhi.smartguard.core.NotifyMessage;
import com.shchuangzhi.smartguard.core.NotifyPrinter;
import com.shchuangzhi.smartguard.core.Student;
import com.shchuangzhi.smartguard.core.StudentState;
import com.shchuangzhi.smartguard.core.Swiper;
import com.shchuangzhi.smartguard.core.TTS;
import com.shchuangzhi.smartguard.core.Teacher;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 */
public class StateButton extends Fragment implements View.OnClickListener {

    private Handler handler1;
    private Handler handler2;
    private DBHelper dbHelper;
    private TextView tvNoInput;

    public StateButton() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_state_button, container, false);

        tvNoInput = (TextView)view.findViewById(R.id.tv_state_no_input);
        tvNoInput.setOnKeyListener(new android.view.View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    String input = tvNoInput.getText().toString().trim();
                    if (input.length() >= 10) {
                        tvNoInput.setText("");
                        String cardNo = input.substring(0, 10).replaceFirst("^0*", "");
                        if(!cardNo.equals("")) {
                            Swiper swiper = dbHelper.getSwiperByCard(cardNo);
                            if (swiper != null) {
                                CheckInOutResult result = swiper.swipe(Mode.getInstance().getCurrent());
                                if (!result.isOk()) {
                                    TTS.get().speak(result.getVoice());
                                }
                            } else {
                                TTS.get().speak(Consts.SPEECH_INVALID);
                            }
                        }
                    }

                    return true;
                }
                return false;
            }
        });

        ImageView btn = (ImageView) view.findViewById(R.id.btn_state_watch);
        btn.setTag(Consts.STATE_WATCH);
        btn.setOnClickListener(this);
        btn = (ImageView) view.findViewById(R.id.btn_state_sick);
        btn.setTag(Consts.STATE_SICK);
        btn.setOnClickListener(this);
        Button btnManual = (Button)view.findViewById(R.id.btn_state_manual);
        btnManual.setOnClickListener(this);

        dbHelper = new DBHelper(this.getActivity());
        addButtons(view, dbHelper.getAllStudentStates());

        handler1 = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                try {
                    NotifyMessage message = (NotifyMessage)msg.obj;
                    addButtons(view, (ArrayList<StudentState>)message.getData());
                } catch(Exception e) {
                    XLog.e("", e);
                }
            }
        };

        final Job dataSyncJob = JobManager.get(Consts.JOB_DATA_SYNC);
        if (dataSyncJob != null) {
            dataSyncJob.addNotify(Consts.NOTIFY_STATE_BUTTON_REFRESH, new Notify() {
                @Override
                public void notify(NotifyMessage message) {
                    handler1.sendMessage(handler1.obtainMessage(Consts.NOTIFY_STATE_BUTTON_REFRESH, message));
                }
            });
        }

        handler2 = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                LinearLayout layout = (LinearLayout)view.findViewById(R.id.btn_group);
                layout.setVisibility(Mode.getInstance().getCurrent() == Consts.IN_MODE ? View.VISIBLE : View.INVISIBLE);
            }
        };

        handler2.sendMessage(handler2.obtainMessage(Consts.NOTIFY_STATE_BUTTON_SWITCH_MODE, null));

        NotifyPrinter.getInstance().addNotify(Consts.NOTIFY_STATE_BUTTON_SWITCH_MODE, new Notify() {
            @Override
            public void notify(NotifyMessage message) {
                handler2.sendMessage(handler2.obtainMessage(Consts.NOTIFY_STATE_BUTTON_SWITCH_MODE, message));
            }
        });

        return view;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_state_manual:{
                doManulCheckInOrOut(tvNoInput.getText().toString().trim());
                tvNoInput.setText("");
            } break;
            default: {
                Student student = Student.getCurrent();
                if (student != null) {
                    if (v.getTag() instanceof Integer) {
                        int state = (int)v.getTag();
                        if (state == Consts.STATE_HEALTH) {
                            return;
                        }
                        CheckInOutResult result = student.swipe(state);
                        if (!result.isOk()) {
                            TTS.get().speak(result.getVoice());
                        } else {
                            TTS.get().speak(StudentState.getStateName(dbHelper, state));
                        }
                    }
                }
            }
        }
    }

    private void addButtons(View view, ArrayList<StudentState> list) {
        LinearLayout parentLayout = (LinearLayout) view.findViewById(R.id.btn_group);
        LinearLayout stateButtonLayout = (LinearLayout)view.findViewById(R.id.layout_button_main_state);
        for(int i = parentLayout.getChildCount() - 1; i >= 0; i--) {
            if (parentLayout.getChildAt(i).getId() != stateButtonLayout.getId()) {
                parentLayout.removeViewAt(i);
            }
        }

        LinearLayout layout = null;
        for (int i = 0; i < list.size();i++) {
            if ((i+1)%3 == 1) {
                layout = new LinearLayout(this.getActivity());
                layout.setLayoutParams(new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                layout.setOrientation(LinearLayout.HORIZONTAL);
                parentLayout.addView(layout);
            }
            Button btn = getButton(list.get(i).getName());
            btn.setTag(list.get(i).getCode());
            btn.setOnClickListener(this);
            layout.addView(btn);
        }
    }

    private Button getButton(String text) {
        Button btn = new Button(this.getActivity());
        btn.setText(text);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.weight = 1;
        btn.setLayoutParams(lp);
        return btn;
    }

    private void doManulCheckInOrOut(String input) {
        try {
            if (Mode.getInstance().getCurrent() == Consts.IN_MODE) {
                if (input != null && !input.equals("")) {
                    Swiper swiper = dbHelper.getSwiperByNo(Integer.parseInt(input));
                    if (swiper != null) {
                        if (swiper.getClass() != Teacher.class) {
                            CheckInOutResult result = swiper.swipe(Mode.getInstance().getCurrent(), true);
                            if (!result.isOk()) {
                                TTS.get().speak(result.getVoice());
                            }
                        } else {
                            TTS.get().speak(Consts.MANUAL_FORBIDDEN);
                        }
                    } else {
                        TTS.get().speak(Consts.SPEECH_INVALID);
                        NotifyPrinter.getInstance().notify(
                                NotifyMessage.info(String.format("%s:%s:3",
                                        Consts.SPEECH_INVALID, input), Consts.NOTIFY_DATA_SYNC, Consts.NOTIFY_DATA_SYC_VIEW_LIST));
                    }
                }
            } else {
                TTS.get().speak(Consts.MANUAL_FORBIDDEN);
            }
        } catch(Exception e) {
            XLog.e("", e);
        }
    }
}
